// http://image.baidu.com/search/index?tn=baiduimage&ie=utf-8&word=%E7%8C%AB%E5%92%AA
// https://ss1.baidu.com/9vo3dSag_xI4khGko9WTAnF6hhy/baike/c0=baike60,5,5,60,20/sign=882eefb055fbb2fb202650402e234bc1/48540923dd54564e439803d4b3de9c82d0584f5a.jpg


const cheerio = require('cheerio')
const cliProgress = require('cli-progress')

const {
  removeDir,
  downloadImage,
  getValueListByReg,
  request,
  mkImageDir
} = require('./common.js')

const bar1 = new cliProgress.SingleBar({
    clearOnComplete: false
}, cliProgress.Presets.shades_classic)

let total = 0
let succeed = 0

const word = '猫咪'

const headers_defalult = {
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Cache-Control': 'max-age=0',
    'Connection': 'keep-alive',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36',
    // '':'',
}
const headers_json = {
  ...headers_defalult,
  'Accept':'text/plain, */*; q=0.01',
}


// 分页请求的地址
// https://image.baidu.com/search/acjson?tn=resultjson_com&ipn=rj&ct=201326592&is=&fp=result&queryWord=%E7%8C%AB%E5%92%AA&cl=2&lm=-1&ie=utf-8&oe=utf-8&adpicid=&st=-1&z=&ic=0&hd=&latest=&copyright=&word=%E7%8C%AB%E5%92%AA&pn=300&rn=30&1631065162301=
// https://image.baidu.com/search/acjson?tn=resultjson_com&logid=12065970787120308096&queryWord=%E6%A3%89%E8%8A%B1ie=utf-8&oe=utf-8&word=%E6%A3%89%E8%8A%B1&pn=60&rn=30&1631022845796=
async function getImageByPage(start, total, word) {
    let allImages = []
    while (start < total) {
        const size = Math.min(60, total - start)
        const url = `https://image.baidu.com/search/acjson?tn=resultjson_com&ipn=rj&ct=201326592&is=&fp=result&queryWord=${encodeURIComponent(word)}&ie=utf-8&oe=utf-8&word=${encodeURIComponent(word)}&pn=${start}&rn=${size}&${Date.now()}=`
        // console.log(url)
        const res = await request(url, headers_json)
        // console.log(res)
        const data = JSON.parse(res.text).data
        // console.log(data)
        allImages = allImages.concat(data)
        start = start + size
    }

    return allImages
}

function runImg(word, counts) {
    request(`http://image.baidu.com/search/index?tn=baiduimage&ie=utf-8&word=${encodeURIComponent(word)}`,headers_defalult)
        .then(async(res) => {
            const htmlText = res.text
                // '"objURL":"https://pic.rmb.bdstatic.com/2fe092eb557ad98eb4fbce076b7a29b6.jpeg",'
            const imageUrlList = getValueListByReg(htmlText, 'objURL')
                // "fromPageTitle":"<strong>猫咪<\/strong>高质量接吻", 
            const titleList = getValueListByReg(htmlText, 'fromPageTitle').map(item => item.replace('<strong>', '').replace('<\\/strong>', ''))
                // console.log(titleList)
            let allImageUrls = imageUrlList.map((imgUrl, index) => ({
                imgUrl,
                title: titleList[index]
            }))

            const firstPageCount = allImageUrls.length
            if (counts > firstPageCount) {
                const restImgUrls = await getImageByPage(firstPageCount, counts, word)
                const formatImgUrls = restImgUrls
                    .filter(v => v.middleURL)
                    .map(item => ({
                        imgUrl: item.middleURL,
                        title: item.fromPageTitle.replace('<strong>', '').replace('</strong>', '')
                    }))
                allImageUrls = allImageUrls.concat(formatImgUrls)
            }
            total = allImageUrls.length
            try {
              const dirName = `images-${word}`
                await mkImageDir(dirName)
                bar1.start(total, 0)
                allImageUrls.forEach((item, index) => {
                    downloadImage(item.imgUrl, item.title, index, dirName).then(res => {
                        succeed++
                        bar1.update(succeed)
                    }).then(res => {
                        if (succeed === total) {
                            bar1.stop()
                            console.log('恭喜您，资源下载完成')
                        }
                    })
                })

            } catch (error) {

            }
        })

}
// runImg('猫咪', 40)
module.exports = {
    runImg
}